<template>
    <div class="search">
        <Row :gutter="16" class="all-height">
            <Col :span="showRight ? 18 : 24" class="all-height">
                <Card class="all-height card-child-height">
                    <Row class="operation code-row-bg" style="display: flex; justify-content: space-between">
                        <Col span="22">
                            <Row class="operation">
                                <Button v-has="'add'" @click="add" type="primary" icon="md-add">添加</Button>
                                <Button v-has="'delete'" @click="delAll" icon="md-trash">批量删除</Button>
                                <Button @click="getDataList" icon="md-refresh">刷新</Button>
                                <Button v-has="'input'" @click="dropImportData">导入学院信息</Button>
                                <Button v-has="'output'" @click="exportAll">导出全部数据</Button>
                                <!--                <Button type="dashed" @click="openSearch=!openSearch">{{openSearch ? "关闭搜索" : "开启搜索"}}</Button>-->
                                <Button type="dashed" @click="openTip = !openTip">{{ openTip ? '关闭提示' : '开启提示' }}</Button>
                            </Row>
                        </Col>
                        <Col span="2" style="text-align: right">
                            <Icon
                                color="#fff"
                                class="icon01"
                                :type="showRight ? `ios-arrow-forward` : `ios-arrow-back`"
                                @click.native="clickShowRight"
                            ></Icon>
                            <!--              <Button-->
                            <!--                  :icon="showRight?`ios-arrow-forward`:`ios-arrow-back`"-->
                            <!--                  @click.native="clickShowRight"-->
                            <!--                  size="mini"-->
                            <!--                  type="primary">-->
                            <!--              </Button>-->
                        </Col>
                    </Row>
                    <Row v-show="openTip">
                        <Alert show-icon>
                            已选择
                            <span class="select-count">{{ selectList.length }}</span>
                            项
                            <a class="select-clear" @click="clearSelectAll">清空</a>
                        </Alert>
                    </Row>
                    <Row class="calc-px-height">
                        <div v-if="loading" class="wh-100 d-flex-around-center">
                            <Spin></Spin>
                        </div>
                        <div v-else v-ref-height="refHeight" class="wh-100">
                            <Table
                                v-if="data.length > 0"
                                border
                                :columns="columns"
                                :data="data"
                                ref="table"
                                sortable="custom"
                                :height="refHeight.value"
                                @on-sort-change="changeSort"
                                @on-selection-change="changeSelect"
                                @on-row-dblclick="sjclaib"
                            ></Table>
                            <div v-else  class="wh-100">
                                <NoData class="wh-100"></NoData>
                            </div>
                        </div>
                    </Row>
                    <Row type="flex" justify="end" class="page">
                        <Page
                            :current="searchForm.pageNumber"
                            :total="total"
                            :page-size="searchForm.pageSize"
                            @on-change="changePage"
                            @on-page-size-change="changePageSize"
                            :page-size-opts="[10, 20, 50, 100, 200]"
                            size="small"
                            show-total
                            show-elevator
                            show-sizer
                        ></Page>
                    </Row>
                </Card>
            </Col>
            <Col span="6" class="all-height" v-show="showRight">
                <Card class="all-height card-child-height">
                    <Row v-show="!modalVisible" @keydown.enter.native="handleSearch">
                        <Col span="24">
                            <div class="drawer-header" style="display: block;">
                                <div class="cmr16">查询区</div>
                            </div>
                        </Col>
                        <Col span="24">
                            <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="marginForm box-marginForm">
                                <FormItem v-if='resource === "1"' label="高校名称" prop="gxmc">
                                    <Input type="text" v-model="searchForm.gxmc" placeholder="请输入高校名称" clearable />
                                </FormItem>
                                <FormItem v-if='resource === "1"' label="高校代码" prop="gxcode">
                                    <Input type="text" v-model="searchForm.gxcode" placeholder="请输入高校代码" clearable />
                                </FormItem>
                                <FormItem label="院系代码" prop="yxcode">
                                    <Input type="text" v-model="searchForm.yxcode" placeholder="请输入院系代码" clearable />
                                </FormItem>
                                <FormItem label="院系名称" prop="yxname">
                                    <Input type="text" v-model="searchForm.yxname" placeholder="请输入院系名称" clearable/>
                                </FormItem>
                                <FormItem class="br box-key">
                                    <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                    <Button @click="handleReset">重置</Button>
                                </FormItem>
                            </Form>
                        </Col>
                    </Row>
                    <Row class="calc-sm-height" v-show="modalVisible">
                        <!-- <Col span="24"> -->
                            <div class="drawer-header">
                                <div class="cmr16">{{ modalTitle }}</div>
                            </div>
                        <!-- </Col> -->
                        <!-- <Col span="24"> -->
                            <Form ref="form" :model="form" :rules="formValidate" :label-width="labelWidth80" label-position="right" class="marginForm">
                                <FormItem label="院系代码" prop="yxcode">
                                    <Input v-model="form.yxcode" clearable />
                                </FormItem>
                                <FormItem label="院系名称" prop="yxname">
                                    <Input v-model="form.yxname" clearable />
                                </FormItem>
                                <FormItem label="排序值" prop="sortorder">
                                    <InputNumber v-model="form.sortorder" style="width: 100%"></InputNumber>
                                </FormItem>
                            </Form>
                        <!-- </Col> -->
                        <div class="br right-bottom-edit">
                            <Button type="text" @click="modalVisible = false">取消</Button>
                            <div v-if="modalType == 0" style="display: inline">
                                <Button v-has="'add'" type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
                            </div>
                            <div v-if="modalType == 1" style="display: inline">
                                <Button v-has="'edit'" type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
                            </div>
                        </div>
                    </Row>
                </Card>
            </Col>
        </Row>

        <!--    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="500">-->

        <!--    </Modal>-->
        <Drawer title="导入数据" closable v-model="importModalVisible" width="1000">
            <div style="display: flex; justify-content: space-between; align-items: center">
                <Upload action :before-upload="beforeUploadImport" accept=".xls, .xlsx">
                    <Button :loading="reading" icon="ios-cloud-upload-outline" class="cmr10">上传Excel文件</Button>
                    <span v-if="uploadfile.name">当前选择文件：{{ uploadfile.name }}</span>
                </Upload>
                <Button @click="clearImportData" icon="md-trash">清空数据</Button>
            </div>
            <Alert type="warning" show-icon>导入前请下载查看导入模版数据文件查看所需字段及说明，确保数据格式正确，不得修改列英文名称</Alert>
            <Table :columns="importColumns" border :height="height" :data="importTableData" ref="importTable"></Table>
            <div class="drawer-footer" style="display: flex; justify-content: space-between">
                <Button @click="downloadTemple" type="info">下载导入模板</Button>
                <div class="wrapper01">
                    <Button @click="importModalVisible = false">关闭</Button>
                    <Button :loading="importLoading" :disabled="importTableData.length <= 0" @click="importData" class="cml8" type="primary">
                        确认导入
                        <span v-if="importTableData.length > 0">{{ importTableData.length }} 条数据</span>
                    </Button>
                </div>
            </div>
        </Drawer>
        <!-- 自定义导出数据 -->
        <Modal v-model="exportModalVisible" :title="exportTitle" :loading="loadingExport" @on-ok="exportCustomData">
            <Form ref="exportForm" :label-width="labelWidth100">
                <FormItem label="导出文件名">
                    <Input v-model="filename" />
                </FormItem>
                <!--        <FormItem label="自定义导出列">-->
                <!--          <CheckboxGroup v-model="chooseColumns">-->
                <!--            <Checkbox-->
                <!--                v-for="(item, i) in exportColumns"-->
                <!--                :label="item.title"-->
                <!--                :key="i"-->
                <!--                :value="item.checked"-->
                <!--                :disabled="item.disabled"-->
                <!--            ></Checkbox>-->
                <!--          </CheckboxGroup>-->
                <!--        </FormItem>-->
            </Form>
        </Modal>
    </div>
</template>

<script>
// 根据你的实际请求api.js位置路径修改
import { getYxManageList, addYxManage, editYxManage, deleteYxManage, importData, getAllCollegeData } from '@/api/bys/yx/yx.js';
import excel from '@/libs/excel';
import { exportColumn } from './yxExportColumn';
import Cookies from 'js-cookie';
import  NoData from '@/components/NoData.vue';
// import {getAllSchoolData} from "@/api";

export default {
    name: 'yxManage',
    components: {
        NoData,
    },
    data() {
        return {
            labelWidth70: 70,
            labelWidth80: 80,
            labelWidth100: 100,
            resource: '',
            height: 510,
            openSearch: true, // 显示搜索
            openTip: true, // 显示提示
            loading: true, // 表单加载状态
            modalType: 0, // 添加或编辑标识
            modalVisible: false, // 添加或编辑显示
            modalTitle: '', // 添加或编辑标题
            height1: 0,
            refHeight: {value: 0},
            searchForm: {
                // 搜索框初始化对象
                pageNumber: 1, // 当前页数
                pageSize: 50, // 页面大小
                sort: 'sortorder', // 默认排序字段
                order: 'asc' // 默认排序方式
            },
            form: {
                // 添加或编辑表单对象初始化数据
                yxcode: '',
                yxname: '',
                sortorder: 0
            },
            // 表单验证规则
            formValidate: {
                yxcode: [{ required: true, message: '不能为空', trigger: 'change' }],
                yxname: [{ required: true, message: '不能为空', trigger: 'change' }]
            },
            submitLoading: false, // 添加或编辑提交状态
            selectList: [], // 多选数据
            columns:[],
            columns_1: [
                // 表头
                {
                    type: 'selection',
                    width: 100,
                    align: 'center'
                },
                {
                    type: 'index',
                    title: '序号',
                    width: 100,
                    align: 'center'
                },
                // {
                //   title: "所属学校",
                //   key: "gxcode",
                //   minWidth: 260,
                //   sortable: false,
                //   render: (h, param) => {
                //     let data = this.schoolDataList.find(e => e.code === param.row.gxcode)
                //     return h('span', data?data.name:param.row.gxcode)
                //   }
                // },
                {
                    title: '学校名称',
                    key: 'gxmc',
                    minWidth: 180,
                    sortable: false
                },
                {
                    title: '院系代码',
                    key: 'yxcode',
                    minWidth: 120,
                    sortable: false
                },
                {
                    title: '院系名称',
                    key: 'yxname',
                    minWidth: 160,
                    sortable: false
                },
                {
                    title: '排序值',
                    key: 'sortorder',
                    minWidth: 120,
                    sortable: true
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    // fixed:"right",
                    minWidth: 120,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'edit') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.edit(params.row);
                                        }
                                    }
                                },
                                '编辑'
                            ),
                            h('Divider', {
                                props: {
                                    type: 'vertical'
                                }
                            }),
                            h(
                                'a',
                                {
                                    style: {
                                        display: this.hasPermission(this, 'delete') ? 'inline-block' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.row);
                                        }
                                    }
                                },
                                '删除'
                            )
                        ]);
                    }
                }
            ],
            data: [], // 表单数据
            total: 0, // 表单数据总数
            importModalVisible: false,
            reading: false,
            importTableData: [],
            importColumns: [],
            exportModalVisible: false,
            uploadfile: {
                name: ''
            },
            importLoading: false,
            exportData: [],
            exportTitle: '确认导出',
            exportColumns: exportColumn,
            showRight: true,
            schoolDataList: []
        };
    },
    methods: {
        tableheig() {
            var bbb = document.getElementsByClassName('calc-px-height')[0].scrollHeight;
            var aaa = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[1];
            var ccc = document.getElementsByClassName('calc-px-height')[0].children[0].children[0].children[0].scrollHeight;
            var ddd = bbb - ccc;
            console.log(bbb, '00000000000000');
            aaa.style.height = `${ddd}px`;

            if (this.searchForm.pageSize === 10) {
                this.height1 = 0;
            } else {
                this.height1 = document.getElementsByClassName('calc-px-height')[0].scrollHeight;
                if (this.total < this.searchForm.pageNumber * this.searchForm.pageSize) {
                    var r = (this.searchForm.pageNumber - 1) * this.searchForm.pageSize;
                    var a = this.total - r;
                    var s = a * 43 + 65;
                    if (s < this.height1) {
                        this.height1 = 0;
                    }
                }
            }
            if (this.total < 10) {
                this.height1 = 0;
            }
        },
        init() {
            this.getDataList();
        },
        // 显示隐藏右侧区域
        clickShowRight() {
            this.showRight = !this.showRight;
        },
        changePage(v) {
            this.searchForm.pageNumber = v;
            this.getDataList();
            this.clearSelectAll();
        },
        changePageSize(v) {
            this.searchForm.pageSize = v;
            this.getDataList();
        },
        handleSearch() {
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            this.getDataList();
        },
        handleReset() {
            this.$refs.searchForm.resetFields();
            this.searchForm.pageNumber = 1;
            this.searchForm.pageSize = 50;
            // 重新加载数据
            this.getDataList();
        },
        changeSort(e) {
            this.searchForm.sort = e.key;
            this.searchForm.order = e.order;
            if (e.order === 'normal') {
                this.searchForm.order = '';
            }
            this.getDataList();
        },
        clearSelectAll() {
            this.$refs.table.selectAll(false);
        },
        changeSelect(e) {
            this.selectList = e;
        },
        getDataList() {
            this.loading = true;
            getYxManageList(this.searchForm).then(res => {
                this.loading = false;
                if (res.success) {
                    this.data = res.result.records;
                    this.total = res.result.total;
                    // this.tableheig();
                    // (this.data.length == 0 && this.searchForm.pageNumber > 1) {
                    //this.searchForm.pageNumber -= 1;
                    //this.getDataList();
                    //}
                }
            });

            // getAllSchoolData().then(res => {
            //   if (res.success){
            //     this.schoolDataList = res.result
            //   }
            // })
        },
        handleSubmit() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    if (!this.form.sortorder) {
                        this.form.sortorder = 0;
                    }
                    this.submitLoading = true;
                    if (this.modalType === 0) {
                        // 添加 避免编辑后传入id等数据 记得删除
                        delete this.form.id;
                        addYxManage(this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.getDataList();
                                this.modalVisible = false;
                            }
                        });
                    } else {
                        // 编辑
                        editYxManage(this.form).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.getDataList();
                                this.modalVisible = false;
                            }
                        });
                    }
                }
            });
        },
        add() {
            this.modalType = 0;
            this.modalTitle = '添加';
            this.$refs.form.resetFields();
            delete this.form.id;
            this.modalVisible = true;
        },
        sjclaib(v) {
            this.showRight = true;
            this.modalType = 1;
            this.modalTitle = '院系编辑区';
            this.$refs.form.resetFields();
            // 转换null为""
            for (let attr in v) {
                if (v[attr] === null) {
                    v[attr] = '';
                }
            }
            let str = JSON.stringify(v);
            let data = JSON.parse(str);
            this.form = data;
            this.modalVisible = true;
        },
        edit(v) {
            this.modalType = 1;
            this.modalTitle = '院系编辑区';
            this.$refs.form.resetFields();
            // 转换null为""
            for (let attr in v) {
                if (v[attr] === null) {
                    v[attr] = '';
                }
            }
            let str = JSON.stringify(v);
            let data = JSON.parse(str);
            this.form = data;
            this.modalVisible = true;
        },
        remove(v) {
            this.$Modal.confirm({
                title: '确认删除',
                // 记得确认修改此处
                content: '您确认要删除该条数据?',
                loading: true,
                onOk: () => {
                    // 删除
                    deleteYxManage({ ids: v.id }).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.clearSelectAll();
                            this.getDataList();
                        }
                    });
                }
            });
        },
        delAll() {
            if (this.selectList.length <= 0) {
                this.$Message.warning('您还未选择要删除的数据');
                return;
            }
            this.$Modal.confirm({
                title: '确认删除',
                content: '您确认要删除所选的 ' + this.selectList.length + ' 条数据?',
                loading: true,
                onOk: () => {
                    let ids = '';
                    this.selectList.forEach(function (e) {
                        ids += e.id + ',';
                    });
                    ids = ids.substring(0, ids.length - 1);
                    // 批量删除
                    deleteYxManage({ ids: ids }).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.clearSelectAll();
                            this.getDataList();
                        }
                    });
                }
            });
        },
        //导入学院数据
        dropImportData() {
            this.importModalVisible = true;
        },
        beforeUploadImport(file) {
            this.uploadfile = file;
            const fileExt = file.name.split('.').pop().toLocaleLowerCase();
            if (fileExt == 'xlsx' || fileExt == 'xls') {
                this.readFile(file);
                this.file = file;
            } else {
                this.$Notice.warning({
                    title: '文件类型错误',
                    desc: '所选文件‘ ' + file.name + ' ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
                });
            }
            return false;
        },
        // 读取文件
        readFile(file) {
            this.reading = true;
            const reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onerror = e => {
                this.reading = false;
                // this.$Message.error("文件读取出错");
                this.$Message.error({
                    content: '文件读取出错',
                    duration: 5,
                    closable: true
                });
            };
            reader.onload = e => {
                const data = e.target.result;
                const { header, results } = excel.read(data, 'array');
                const tableTitle = header.map(item => {
                    return { title: item, key: item, minWidth: 130, align: 'center' };
                });
                this.importTableData = results;
                this.importColumns = tableTitle;
                this.reading = false;
                this.$Message.success('读取数据成功');
            };
        },
        clearImportData() {
            this.importTableData = [];
            this.importColumns = [];
            this.uploadfile = {};
        },
        downloadTemple() {
            // alert(process.env.BASE_URL + "院系导入模板.xlsx","process.env.BASE_URL + \"用户导入模板.xlsx\"")
            window.location.href = process.env.BASE_URL + '院系导入模板.xlsx';
        },
        importData() {
            let params = this.importTableData.map(item => {
                return {
                    yxcode: item['院系代码'],
                    yxname: item['院系名称'],
                    sortorder: item['排序号']
                };
            });
            this.importLoading = true;
            importData(params).then(res => {
                this.importLoading = false;
                if (res.success) {
                    this.importModalVisible = false;
                    this.getDataList();
                    this.$Modal.info({
                        title: '导入结果',
                        content: res.message
                    });
                }
            });
        },
        //导出全部信息
        async exportAll() {
            this.getDataList();
            let columns = this.exportColumns.filter(item => item.key != 'action' && item.type != 'selection' && item.type != 'index');
            let title = columns.map(item => item.title);
            let key = columns.map(item => item.key);
            let data = this.data.map((item, i) => {
                item.i = i + 1;
                // // 将字典代码替换为字典值dictAseetStatus
                // let distributionStatusDict = this.dictAseetStatus.find(d => d.value == item.assetStatus);
                // item.assetStatus = distributionStatusDict ? distributionStatusDict.title : '';
                // let assetTypeDict = this.dictAseetType.find(d => d.value == item.type);
                // item.type = assetTypeDict ? assetTypeDict.title : '';
                // let assetKindDict = this.treeData.find(d => d.code == item.kind);
                // item.kind = assetKindDict ? assetKindDict.title : '';
                return item;
            });
            if (data === undefined || data === 'undefined') {
                data = '';
            }
            const params = {
                title: ['序号', ...title],
                key: ['i', ...key],
                data: data,
                autoWidth: true,
                filename: '学院全部信息数据'
            };
            excel.export_array_to_excel(params);
        },
        onRestWindow() {
            this.columns = this.restTableCellWidth(this.columns_1)
            this.labelWidth80 = this.searchLabelWidth(this.labelWidth80)
            this.labelWidth70 = this.searchLabelWidth(this.labelWidth70)
            this.labelWidth100 = this.searchLabelWidth(this.labelWidth100)
        },
    },
    beforeDestroy() {
        window.removeEventListener('resize',this.onRestWindow)
    },
    mounted() {
        this.onRestWindow()
        window.addEventListener('resize',this.onRestWindow)

        let resource = JSON.parse(Cookies.get('userInfo')).resource;
        this.resource = resource
        this.height = Number(document.documentElement.clientHeight - 230);
        this.init();
    }
};
</script>
<style lang="less">
// 建议引入通用样式 具体路径自行修改 可删除下面样式代码
@import '../../../styles/table-common.less';
@import '../../personInfo.less';
.calc-sm-height {
    flex-direction: column;
}
.marginForm {
    flex-grow: 1;
}
.search {
    .operation {
        margin-bottom: 2vh;
    }

    .select-count {
        font-weight: 600;
        color: #40a9ff;
    }

    .select-clear {
        margin-left: 10px;
    }

    .page {
        margin-top: 2vh;
    }

    .drop-down {
        margin-left: 5px;
    }
}

</style>
<style lang="less" scoped>
.icon01 {
    background: rgb(45, 154, 244); border-radius: 50%; padding: 3px
}
.cmr16 {
    margin-right: 16px
}
.cw200{
    width: 200px
}
.cml-35 {
    margin-left: -35px
}
.cmr10 {
    margin-right: 10px
}
.wrapper01 {
    position: absolute; right: 15px; display: inline-block
}
.cml8 {
    margin-left: 8px
}

@media (max-width: 1920px) {
    /deep/ .ivu-table .ivu-table-fixed-right{
        height: 98% !important;
    }
    /deep/ .ivu-table .ivu-table-fixed-right  .ivu-table-fixed-body {
    height: 94% !important;
    }
    /deep/ .ivu-table-body {
        height: 94% !important;
    }
}
</style>
<style scoped lang="less">
.box-marginForm {
    margin-top: 20px;
}
// 重构样式
/deep/ .ivu-form-item-label{
    display: flex;
    justify-content: right;
    width: 150px !important;
}
/deep/ .ivu-form-item {
    width: 100%;
    margin-bottom: 0.1rem;
    margin-right: 0 !important;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
/deep/ .ivu-form-item-content {
    width: 100% !important;
    margin-left: 0 ! important;
}
/deep/ .ivu-select {
    width: 100% !important;
}
/deep/ .ivu-date-picker {
    width: 100% !important;
}
/deep/ .br {
    margin-top: 15px;
    bottom: 0.12rem !important;
    .ivu-form-item-content {
        display: flex;
    }
}
/deep/ .ivu-input-type-textarea,/deep/ .ivu-input {
    height: calc(100% - 7px) !important;
}
.flex-1 {
    height: 100%;
}
/deep/ .ivu-drawer-body {
    overflow: hidden;
    .d-flex-align-center {
        height: fit-content !important;
        margin-left: 0 !important;
        justify-content: right;
        box-sizing: border-box;
        padding-right: 7px;
    }
}
.box-key {
    /deep/ .ivu-form-item-content {
        margin-left: 102px !important;
    }
}
</style>